from socket import *
# 单线程实现非阻塞IO模型
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", 8080))

serverSocket.listen(5)
serverSocket.setblocking(False) # 非阻塞 没有客户端连接会抛出BlockingIOError错误

clientList = []

while True:
  # clientSocket, clientInfo = serverSocket.accept()
  try:
    newSocket, clientAddr = serverSocket.accept()
  except BlockingIOError:
    pass
  else:
    print('new client arrived: %s'%str(clientAddr))
    newSocket.setblocking(False)
    clientList.append((newSocket, clientAddr))
  
  for clientSocket, clientAddr in clientList:
    try: 
      recvData = clientSocket.recv(1024)
    except BlockingIOError:
      pass
    else:
      if len(recvData) > 0: # 当客户端关闭连接的时候 会发送一个长度为零的数据
        print("%s : %s --> %d"%(str(clientAddr), recvData, len(clientList)))
      else:
        clientSocket.close()
        clientList.remove((clientSocket,clientAddr))
      

    # recvData = clientSocket.recv(1024).decode('gbk')
    # print('------------2-------------')
    # print('------------3-------------')

  # clientSocket.close()